#include<stdio.h>
#include<pthread.h>

//饿汉模式
#if 0
class sigleton{
    private:
        sigleton(){}
        static sigleton* st;
    public:
        static sigleton* GetInstance();
        void print(){
            printf("hhhh\n");
        }
};
//程序一旦启动，就创建了全局唯一的实例对象
sigleton* sigleton::st = new sigleton();
sigleton* sigleton::GetInstance(){
    return st;
}
#endif

//懒汉模式
class sigleton{
    private:
        sigleton(){}
        static sigleton* st;
        static pthread_mutex_t _lock;
    public:
        static sigleton* GetInstance();
        void print(){
            printf("hhhhh\n");
        }
};
sigleton* sigleton::st = NULL;
pthread_mutex_t sigleton::_lock = PTHREAD_MUTEX_INITIALIZER;

sigleton* sigleton::GetInstance(){
    if(st == NULL){
        pthread_mutex_lock(&_lock);  //当第二个线程紧跟第一个时，加锁等待，降低锁冲突概率，提高性能
        if(st == NULL){
            st = new sigleton;
        }
        pthread_mutex_unlock(&_lock);
    }
    return st;
}


int main(){
    sigleton* st1 = sigleton::GetInstance();
    sigleton* st2 = sigleton::GetInstance();
    st1->print();
    if(st1 == st2){
        printf("st1 == st2\n");
    }
    return 0;
}
